require('./../models/curso.model');
var DBAccess = require('./db');

function CursoDAO() {
    var db = DBAccess.getInstance();
    var model = db.model('Curso');

    this.add = function(curso, callback) {
        var args = arguments;
        db.connect();
        curso.save(function(err) {
            if (err) throw err;
            else if (args.length === 2 && typeof args[1] == 'function')
                callback();
        });
    }

    this.remove = function(curso, callback) {
        var args = arguments;
        db.connect();
        model.remove({nome: curso.nome}, function(err, doc) {
            if (err) throw err;
            else if (args.length === 2 && typeof args[1] == 'function')
                callback();
        });
    }

    this.get = function(curso, callback) {
        db.connect();
        model.findOne({nome: curso.nome}, callback);
    }

    this.getById = function(id, callback) {
        db.connect();
        model.findById(id, callback);
    }

    //FIXME
    this.update = function(id, update) {
        db.connect();
        model.findOne({nome: id}, function(err, old){
            if(!old)
                throw new Error('Curso not found!');
            old.nome = update.nome || old.nome;
            old.departamento = update.departamento || old.departamento;
            old.save(function(err) {
                if(err) throw err;
            });
        });
    }

    this.getAll = function(callback) {
        db.connect();
        if(typeof callback != 'function')
            throw new Error('Give me a callback function!');
        model.find({}, function(err, all) {
            callback(err, all);
        });
    }

    this.getModel = function() {
        return new model();
    }

}

module.exports = CursoDAO;
